﻿using CloudStorageLight.Core.Web;
using Microsoft.WindowsAzure.Storage.Table;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace CloudStorageLight.Core
{

    /// <summary>
    /// ログアイテム
    /// </summary>
    public class AccessLog : TableEntity
    {
        public AccessLog()
        {

        }
        public AccessLog(string accountName, DateTime date)
        {
            var guid = Guid.NewGuid();
            this.PartitionKey = (accountName ?? "") + "_" + date.ToString("yyyyMMdd");
            this.RowKey = string.Format("{0}-{1}", date.ToString("yyyyMMdd HH:mm:ss:fff"), Guid.NewGuid().ToString());
            this.IPAddress = WebUtil.GetIPAddress();
        }
        public DateTime Date 
        { 
            get 
            { 
                var d = DateTime.ParseExact(this.RowKey.Split('-')[0], "yyyyMMdd HH:mm:ss:fff", null, System.Globalization.DateTimeStyles.AssumeUniversal);
                return d;
            } 
        }

        public string UserName { get; set; }

        public string AccountName 
        { 
            get 
            {
                var len = this.PartitionKey.Length - 9;
                if (len < 0) len = 0;
                return this.PartitionKey.Substring(0, len); 
            } 
        }

        public string Action { get; set; }

        public string Path { get; set; }

        public string IPAddress { get; set; }

        public string Additional { get; set; }

        public override string ToString()
        {
            return Date.ToString("D") + ":" + (UserName ?? "UNKNOWN") + "/" + (Action ?? "")  + "/" + (Path ?? "") + (string.IsNullOrEmpty(Additional) ? "" :( "(" + Additional + ")"));
        }
    }
}
